package kom;

import java.awt.Graphics2D;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Ziden
 */
public class Effects {

    // effect types
    public enum EffectType {
        SMOKE(0),
        SPARK(1);
        
        private final int id;
        EffectType(int id) {
            this.id = id;
        }
    }
    private List<AnimatedEffect> effectsRunning = new LinkedList<AnimatedEffect>();

    public void playEffect(int x, int y, EffectType type, int xOffset, int yOffset) {
        AnimatedEffect eff = new AnimatedEffect(x, y, type, xOffset, yOffset);
        if (type == EffectType.SMOKE) {
            eff.maxFrame = 6;
        }
        effectsRunning.add(eff);
    }

    public void playEffect(AnimatedEffect eff) {
        effectsRunning.add(eff);
    }

    public void tick() {
        for (AnimatedEffect effect : effectsRunning) {
            effect.positionTick();
            effect.tickCount++;
            if (effect.tickCount >= effect.ticksToFrame) {
                if (effect.rewinding) {
                    effect.frame--;
                } else {
                    effect.frame++;
                }
                effect.tickCount = 0;
            }
            if (effect.rewinding && effect.frame == -1) {
                toRemove.add(effect);
            }
            if (effect.frame == effect.maxFrame) {
                if (effect.rewind) {
                    effect.rewinding = true;
                    effect.frame--;
                } else {
                    toRemove.add(effect);
                }

            }

        }

        effectsRunning.removeAll(toRemove);
        toRemove.clear();
    }
    private List<AnimatedEffect> toRemove = new LinkedList<AnimatedEffect>();

    public void renderEffects(Graphics2D g, Bitmaps bitmaps, int xoffs, int yoffs) {
        for (AnimatedEffect effect : effectsRunning) {
            g.drawImage(bitmaps.animatedEffects.get(effect.type.id)[effect.frame], (int) effect.x + effect.xOffset - xoffs, (int) effect.y + effect.yOffset - yoffs, null);
        }
    }

    public AnimatedEffect getNewEffect(int x, int y, EffectType type, int xOffset, int yOffset) {
        return new AnimatedEffect(x, y, type, xOffset, yOffset);
    }

    public class AnimatedEffect extends Entity {

        public boolean rewinding = false;
        public boolean rewind = false;
        public EffectType type;
        public int frame;
        public int maxFrame;
        public int ticksToFrame = 3;
        public int tickCount = 0;
        // internal offsets to make the sprites more 'accurate' if needed
        public int xOffset = 0;
        public int yOffset = 0;

        public AnimatedEffect(int x, int y, EffectType type, int xOffset, int yOffset) {
            this.x = x;
            this.y = y;
            this.type = type;
            this.xOffset = xOffset;
            this.yOffset = yOffset;
            width = 16;
            height = 16;
        }
    }
}
